package helper

import (
	"fmt"
	"log"
	"net/smtp"
	"os"
	"sync"
	"time"
	"github.com/jordan-wright/email"
)

func init(){
	fmt.Println("是否执行了前置函数")

}

func SendEmail(toEmail string,code int64){
	ch := make(chan *email.Email, 2)
	p, err := email.NewPool(
		"smtp.qq.com:25",
		4,
		smtp.PlainAuth("", "1124378213@qq.com", "kldrznlkqtiwhgbg", "smtp.qq.com"),
	)

	if err != nil {
		log.Fatal("failed to create pool:", err)
	}

	var wg sync.WaitGroup
	wg.Add(4)
	for i := 0; i < 4; i++ {
		go func() {
			defer wg.Done()
			for e := range ch {
				err := p.Send(e, 10*time.Second)
				if err != nil {
					fmt.Fprintf(os.Stderr, "email:%v sent error:%v\n", e, err)
				}
			}
		}()
	}

	//for i := 0; i < 2; i++ {
	//	e := email.NewEmail()
	//	e.From = "1124378213@qq.com"
	//	e.To = []string{"657106593@qq.com"}
	//	e.Subject = "Awesome web"
	//	e.Text = []byte(fmt.Sprintf("Awesome Web %d", i+1))
	//	ch <- e
	//}

	//发送验证码
	e := email.NewEmail()
	e.From = "雷小天社区<1124378213@qq.com>"
	e.To = []string{toEmail}
	e.Subject = "雷小天社区注册验证码"
	e.Text = []byte(fmt.Sprintf("本次注册验证码： %d", code))
	ch <- e

	//发送联动邮件
	e = email.NewEmail()
	e.From = "雷小天社区<1124378213@qq.com>"
	e.To = []string{toEmail}
	e.Subject = "雷小天社区联动邮件"
	e.Text = []byte(fmt.Sprintf("本次邮件由验证码触发，验证码90秒过期，欢迎浏览雷小天社区！"))
	ch <- e

	close(ch)
	wg.Wait()
}